package com.xzone.material.security.authentication

import com.xzone.material.security.service.TokenService
import com.xzone.material.user.service.UserService
import jakarta.servlet.FilterChain
import jakarta.servlet.http.HttpServletRequest
import jakarta.servlet.http.HttpServletResponse
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken
import org.springframework.security.core.authority.AuthorityUtils
import org.springframework.security.core.context.SecurityContextHolder
import org.springframework.stereotype.Component
import org.springframework.web.filter.OncePerRequestFilter


@Component
class JwtSecurityFilter(
    private val userService: UserService,
    private val tokenService: TokenService
) : OncePerRequestFilter() {

    override fun doFilterInternal(request: HttpServletRequest, response: HttpServletResponse, chain: FilterChain) {
        if (SecurityContextHolder.getContext().authentication == null) {
            val jwt: String? = request.getParameter("jwt") // TODO 获取jwt
            if (jwt != null && tokenService.checkToken(jwt)) {

                // 从jwt中获取userid
                val user = userService.findById(tokenService.getUserId(jwt))
                val token = UsernamePasswordAuthenticationToken(user, null, AuthorityUtils.NO_AUTHORITIES)
                //这一步是核心，将验证信息放入到SecurityContext，表明已经认证成功
                SecurityContextHolder.getContext().authentication = token
            }
        }
        chain.doFilter(request, response)
    }
}